package com.kfgj.hkp.common.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfgj.hkp.common.exception.BaseException;
import com.kfgj.hkp.common.exception.ExceptionEvent;
import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import com.kfgj.hkp.common.service.AbstractServiceResponse;
import com.kfgj.hkp.common.utils.ExceptionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by liwensihan on 2018/5/16.
 */
public abstract class AbstractSpringInterceptor extends HandlerInterceptorAdapter {

    protected ObjectMapper objectMapper = new ObjectMapper();

    protected static Logger logger = LoggerFactory.getLogger(AbstractSpringInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {

            return preInterceptor(request, response, handler);

        } catch (Exception e) {

            //
            AbstractServiceResponse result = new AbstractServiceResponse();
            result.setIsSuccess(false);
            result.setIsException(true);

            if (logger.isDebugEnabled()){
                result.setStackTrace(ExceptionUtils.getStackTrace(e));
            }


            if (e instanceof BaseException){
                result.setMessage(((BaseException)e).getErrorMsg());
                result.setCode(((BaseException)e).getCode());
            }else{
                result.setMessage(e.getMessage());
                result.setCode(ExceptionEvent.unKnownErrorCode);
            }

            writeJsonError(response,result);

            return false;

        }
    }


    protected abstract boolean preInterceptor(HttpServletRequest request, HttpServletResponse response, Object handler);

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    protected void writeJsonError(HttpServletResponse response, Object result) {

        response.setContentType("application/json;charset=UTF-8");
        try {
            PrintWriter pw = response.getWriter();
            pw.write(objectMapper.writeValueAsString(result));
            pw.flush();
        } catch (IOException e) {

            logger.error("interceptor invoke jsonError error ", e);

        }
    }
}
